package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.util.BaseContext;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 接收手机号发送短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码是{}", code);
            //调用阿里云提供的短信服务api完成发送短信
            //SMSUtils.sendMessage("吉瑞外卖","",phone,code);
            //需要将生成的验证码保存的session
           // session.setAttribute("phonecode", code);

            redisTemplate.opsForValue().set(phone,code,6, TimeUnit.MINUTES);
            return R.success("短信验证码发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //String codeInSession = (String) session.getAttribute("phonecode");
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);
        //判断验证码是否正确
        if (codeInSession.equals(code) ) {
            //正确则登录成功
            redisTemplate.delete(phone);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);

            User user = userService.getOne(queryWrapper);
            User newuser = new User();
            if (user == null) {
                //判断用户是否为新用户，如果不是自动注册
                newuser.setPhone(phone);
                userService.save(newuser);
                session.setAttribute("user", newuser.getId());
            } else {
                session.setAttribute("user", user.getId());
            }
            return R.success(newuser);
        }
        return R.error("登录失败");
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session) {

        session.removeAttribute("user");
        return R.success("退出成功");
    }

}
